package com.mp.license.controller;

import com.mp.ipm2020.common.api.CommonResult;
import com.mp.ipm2020.common.license.AbstractServerInfos;
import com.mp.ipm2020.common.license.LicenseCheckModel;
import com.mp.ipm2020.common.license.LinuxServerInfos;
import com.mp.ipm2020.common.license.WindowsServerInfos;
import com.mp.license.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther adidasshe@mp.cn
 * <p>
 * 证书生成
 */
@RestController
@RequestMapping("/license")
public class LicenseCreatorController {

    /**
     * 证书subject
     */
    @Value("${license.subject}")
    private String subject;

    /**
     * 密钥别称
     */
    @Value("${license.privateAlias}")
    private String privateAlias;

    /**
     * 密钥密码（需要妥善保管，不能让使用者知道）
     */
    @Value("${license.keyPass}")
    private String keyPass;

    /**
     * 访问秘钥库的密码
     */
    @Value("${license.storePass}")
    private String storePass;

    /**
     * 证书生成路径
     */
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    private String privateKeysStorePath;

    /**
     * 描述信息
     */
    @Value("${license.description}")
    private String description;


    @GetMapping
    public CommonResult getServerInfos() {
        //操作系统类型
        String osName = System.getProperty("os.name").toLowerCase();

        AbstractServerInfos abstractServerInfos = null;

        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        } else {//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }

        return CommonResult.success(abstractServerInfos.getServerInfos());
    }


    @PostMapping
    public CommonResult generate(@RequestBody(required = true) LicenseCreatorParam param) {
        //获取项目路径
        String projectPath = System.getProperty("user.dir");
        licensePath = projectPath + "/license/src/main/resources/license/license.lic";
        privateKeysStorePath = projectPath + "/license/src/main/resources/license/privateKeys.keystore";
        //使用配置的参数
        param.setSubject(subject);
        param.setPrivateAlias(privateAlias);
        param.setKeyPass(keyPass);
        param.setStorePass(storePass);
        param.setLicensePath(licensePath);
        param.setPrivateKeysStorePath(privateKeysStorePath);
        param.setDescription(description);

        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if (result) {
            System.out.println("证书生成成功" + "======================");
            return CommonResult.success(param);
        } else {
            return CommonResult.failed("证书文件生成失败！");
        }

    }

    /**
     * 生成证书
     *
     * @param param 生成证书需要的参数，如：{
     *              "subject":"ipm2020",
     *              "privateAlias":"privateKey",
     *              "keyPass":"5T7Zz5Y0dJFcqTxvzkH5LDGJJSGMzQ",
     *              "storePass":"3538cef8e7",
     *              "licensePath":"E:/ys/ipm2019/java/ipm2020/license.lic",
     *              "privateKeysStorePath":"E:/ys/ipm2019/java/ipm2020/privateKeys.keystore",
     *              "issuedTime":"2020-06-30 09:48:12",
     *              "expiryTime":"2022-12-31 00:00:00",
     *              "consumerType":"User","consumerAmount":1,
     *              "description":"这是证书描述信息",
     *              "licenseCheckModel":{
     *              "macAddress":[
     *              "C0-B6-F9-42-25-CA",
     *              "00-50-56-C0-00-01",
     *              "00-50-56-C0-00-08"
     *              ],
     *              "cpuSerial":"",
     *              "mainBoardSerial":""}
     *              }
     * @return
     */
    @PostMapping("/generate")
    public CommonResult generateLicense(@RequestParam String expiryTime, @RequestParam String macAddress,
                                        @RequestParam String cpuSerial, @RequestParam String mainBoardSerial)
            throws ParseException {
        //获取项目路径
        String projectPath = System.getProperty("user.dir");
        licensePath = projectPath + "/license/src/main/resources/license/license.lic";
        privateKeysStorePath = projectPath + "/license/src/main/resources/license/privateKeys.keystore";
        //格式化页面时间参数
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //格式化mac地址列表
        List<String> macList = Arrays.asList(macAddress.split(",")).stream().map(s -> String.format(s.trim())).
                collect(Collectors.toList());
        System.out.println(expiryTime + macList);
        //设置默认证书生成参数
        LicenseCreatorParam param = new LicenseCreatorParam();
        LicenseCheckModel licenseCheckModel = new LicenseCheckModel();
        //设置自定义需要校验的License参数
        licenseCheckModel.setMacAddress(macList);
        licenseCheckModel.setCpuSerial(cpuSerial);
        licenseCheckModel.setMainBoardSerial(mainBoardSerial);
        //设置License参数
        param.setExpiryTime(simpleDateFormat.parse(expiryTime));
        param.setLicenseCheckModel(licenseCheckModel);
        param.setSubject(subject);
        param.setDescription(description);
        param.setKeyPass(keyPass);
        param.setStorePass(storePass);
        param.setLicensePath(licensePath);
        param.setPrivateAlias(privateAlias);
        param.setPrivateKeysStorePath(privateKeysStorePath);
        LicenseCreator licenseCreator = new LicenseCreator(param);
        boolean result = licenseCreator.generateLicense();

        if (result) {
            System.out.println("证书生成成功" + "======================");
            return CommonResult.success(param);
        } else {
            return CommonResult.failed("证书文件生成失败！");
        }

    }

}
